import { login,regist,logout } from '@/api/login'
import { getToken,setToken } from '@/utils/auth'

const user = {
  state: {
    username:'',
    token:''
  },

  mutations: {
    SET_NAME: (state, username) => {
      state.username = username;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
      setToken(token);
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password.trim();
      return new Promise((resolve, reject) => {
        login(username, password).then(response => {
          const data = response.data;
          commit('SET_NAME', data.username);
          commit('SET_TOKEN', data.token);
          setUsername(data.username);
          setToken(data.token);
          resolve(response); }).catch(error => { reject(error) }) }) },
    // 注册
    Regist({ commit }, userInfo) {
      const username= userInfo.username.trim();
      const password = userInfo.password.trim();
      return new Promise((resolve, reject) => {
        regist(username, password).then(response => {
          const data = response.data;
          commit('SET_NAME', data.username);
          commit('SET_TOKEN', data.token);
          setUsername(data.username);setToken(data.token);
          resolve(response);
        }).catch(error => {
          reject(error) }) }) },
    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(response => {
          commit('SET_USERNAME', '');
          commit('SET_TOKEN', '');
          setUsername('');
          setToken(false);
          //removeName();
          //removeToken();
          resolve(response);
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        setToken(false);
        commit('SET_TOKEN', false);
        resolve()
      })
    }
  }
}
export default user


const getters={
  name:state=>state.user.username,
  token:state=>state.user.token
}
export default getter
